import {useEffect, useState} from "react";
/*
* 引入PubSub
* */
import PubSub from "pubsub-js"
import "./styles/index.css"
import Header from "./components/Header/Header";
import Main from "./components/Main/Main";
import Footer from "./components/Footer/Footer";


function App() {
    /*
    * 代办任务列表
    * */
    const [todoList, setTodoList] = useState([
        {id: 1, checked: true, text: "java"},
        {id: 2, checked: true, text: "JavaScript"},
        {id: 3, checked: true, text: "php"},
    ])

    /*
    * 添加todo的回调函数(传递给子组件header，header组件调用传递todo)
    * */
    const addTodo = (todo) => {
        const newTodoList = [...todoList, todo]
        setTodoList(newTodoList)
    }

    /*
    * 删除todo的回调函数
    * */
    const deleteTodo = () => {
        // 订阅消息 第一个参数为消息名：deleteTodo  第二个参数为一个待执行的函数
        // 此函数又有两个参数：消息名和消息数据
        PubSub.subscribe("deleteTodo", (msg, id) => {
            const newTodoList = todoList.filter(todo => todo.id !== id)
            setTodoList(newTodoList)
        })
    }


    /*
    * 全选与取消全选所有的todo的回调函数
    * */
    const changeCheckedAll = (checked) => {
        const newTodoList = [...todoList]
        newTodoList.forEach(todo => todo.checked = checked)
        setTodoList(newTodoList)

    }

    /*
    * 勾选或者不勾选todo的回调函数
    * */
    const changeChecked = () => {
        // 订阅消息 第一个参数为消息名：changechecked  第二个参数为一个待执行的函数
        // 此函数又有两个参数：消息名和消息数据
        PubSub.subscribe("changeChecked", (msg, {id, checked}) => {
            const newTodoList = [...todoList]
            const todo = newTodoList.find(todo => todo.id === id)
            todo.checked = !checked
            setTodoList(newTodoList)
        })
    }

    /*
    * 删除所有todo的回调函数
    * */
    const deleteAllTodo = () => {
        setTodoList([])
    }

    /*
     * 删除已经完成todo的回调函数
     * */
    const deleteCheckedTodo = () => {
        const newTodoList = todoList.filter(todo => !todo.checked)
        setTodoList(newTodoList)
    }
    /*
    * 是否全选
    * */
    const isCheckedAll = () => todoList.every(todo => todo.checked) && todoList.length !== 0


    /*
    * 完成的todo
    * */
    const checkedTotal = todoList.filter(todo => todo.checked).length

    /*
    * 所有的todo
    * */
    const total = todoList.length

    /*
     * 组件挂载相当于componentDidmounted
     * */
    useEffect(() => {
        deleteTodo()
        changeChecked()
    });
    return (
        <div className="App">
            <Header addTodo={addTodo}></Header>
            <Main todoList={todoList}></Main>
            <Footer total={total} checkedTotal={checkedTotal} isCheckedAll={isCheckedAll()} changeCheckedAll={changeCheckedAll} deleteAllTodo={deleteAllTodo} deleteCheckedTodo={deleteCheckedTodo}></Footer>
        </div>
    );
}

export default App;
